<?php

/**
 * 
 * 
 *
 */
class Quad_Form_Elements extends Quad_Iterable {
	
	protected $_form;
	
  public function __construct(Quad_Form $form) {
    $this->_form = $form;
		parent::__construct();
  }
  
  public function __get($p) {
		if ($p == 'length') {
			if ($this->_array['length']) {
				return $this->_array['length'];
			}
			else {
				return $this->count();
			}
		}
		foreach ($this->_array as $el) {
			if ($el->name == $p) {
				return $el;
			}
		}
		return null;
  }
  
  public function __set($p, $v) {
  	if ($v instanceof Quad_Form_Element) {
  		$this->_array[] = $v;
  		// automatically set appropriate enctype for file inputs
			if ($v instanceof Quad_Form_Element_File) {
				$this->_form->enctype = 'multipart/form-data';
			}
  	}
  	if ($p == 'length') {
  		throw new Quad_Form_Exception('Quad_Form_Elements->length is read only.');
  	}
  	$this->$p = $v;
  }
  
  // ArrayAccess Interface Functions
  public function offsetExists($offset) {
    return isset($this->_array[$offset]);
  }

  public function offsetGet($offset) {
    return $this->_array[$offset];
  }
 
  public function offsetSet($offset, $value) {
  	if ($value instanceof Quad_Form_Element) {
  		$this->_array[$offset] = $value;
  	}
  }
 
  public function offsetUnset($offset) {
  	$v = $this->_array[$offset];
  	$isFile = ($v instanceof Quad_Form_Element_File);
  	unset($this->_array[$offset]);
  	// renumber the array
  	$this->_array = array_values($this->_array);
  	// if file input is removed and no other file inputs remain, unset enctype
  	if ($isFile && $this->_form->enctype == 'multipart/form-data') {
	  	foreach ($this->_array as $el) {
	  		if ($el instanceof Quad_Form_Element_File) {
	  			return;
	  		}
	  	}
	  	unset ($this->_form->enctype);
  	}
  }
  
}